package com.xinziruo.crawl.infrastruture.support.filter;

import static com.xinziruo.crawl.infrastruture.support.command.CommandConstant.ONLINE;
import static com.xinziruo.crawl.infrastruture.support.command.CommandConstant.OUTLINE;

import org.apache.mina.core.filterchain.IoFilterAdapter;
import org.apache.mina.core.session.IoSession;

import com.xinziruo.crawl.infrastruture.support.command.Command;
import com.xinziruo.crawl.infrastruture.support.server.CommandClientHolder;

/**
 * 
 * @author loudyn
 * 
 */
public class CommandClientInjectFilter extends IoFilterAdapter {

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * org.apache.mina.core.filterchain.IoFilterAdapter#exceptionCaught(org.apache.mina.core.filterchain.IoFilter.NextFilter
	 * , org.apache.mina.core.session.IoSession, java.lang.Throwable)
	 */
	@Override
	public void exceptionCaught(NextFilter nextFilter, IoSession session, Throwable cause) throws Exception {
		CommandClientHolder.remove(session);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * org.apache.mina.core.filterchain.IoFilterAdapter#messageReceived(org.apache.mina.core.filterchain.IoFilter.NextFilter
	 * , org.apache.mina.core.session.IoSession, java.lang.Object)
	 */
	@Override
	public void messageReceived(NextFilter nextFilter, IoSession session, Object message) throws Exception {

		if (!isCommandMessage(message)) {
			throw new UnsupportedOperationException("Received message must represent a command object!");
		}

		Command comm = (Command) message;

		switch (comm.contentType()) {
		case ONLINE:
			CommandClientHolder.put(session);
			break;
		case OUTLINE:
			CommandClientHolder.remove(session);
			break;

		default:
			super.messageReceived(nextFilter, session, message);
			break;
		}
	}

	private boolean isCommandMessage(Object message) {
		return Command.class.isAssignableFrom(message.getClass());
	}
}
